<?php
/**
 * Created by AI Assistant
 * User: Administrator
 * Date: 2025-10-09
 * Time: 12:00
 */

namespace plugin\csauto\app\process;


use plugin\csauto\app\model\TorrentReleaseModel;
use plugin\csauto\app\service\downloader\DownloaderWorkService;
use support\Log;
use Workerman\Crontab\Crontab;
use Workerman\Timer;

/**
 * Class TaskPushTorrentProcess
 * 步骤8
 * 专门处理已发布任务的种子推送操作
 * 从 TaskReleaseProcess 中拆分出来，独立线程处理
 *
 * @package plugin\csauto\app\process
 */
class TaskPushTorrentProcess
{
    // 定时器句柄/ID
    protected $timer;
    
    // 时间间隔 (单位: 秒, 每5秒处理一个任务)
    protected $interval = 5;

    public function onWorkerStart()
    {
        if (getenv('WORK_DEBUG')) return true;
        $this->timer = Timer::add($this->interval, function () {
            try {
                // 这里执行系统预设的定时任务事件
                $this->run();
            } catch (\Throwable $e) {
                // 构建完整的错误信息
                $errorMessage = "ERROR[TaskPushTorrentProcess]:" . PHP_EOL;
                $errorMessage .= "Message: " . $e->getMessage() . PHP_EOL;
                $errorMessage .= "File: " . $e->getFile() . PHP_EOL;
                $errorMessage .= "Line: " . $e->getLine() . PHP_EOL;
                $errorMessage .= "Code: " . $e->getCode() . PHP_EOL;
                $errorMessage .= "Trace:" . PHP_EOL . $e->getTraceAsString() . PHP_EOL;

                echo $errorMessage;
            }
        });

        return true;
    }

    public function run()
    {
        // 处理已发布任务的种子推送
        // 查询状态为2（已发布）、task_status为1（任务进行中）、torrents_hash为空（尚未推送）的任务
        // 每次只处理一个任务
        $item = TorrentReleaseModel::where('status', 2)
            ->where('task_status', 1)
            ->where('torrents_hash', '')
            ->orderBy('updated_at')
            ->first();
        
        if (!$item) {
            // 没有待处理任务
            return '无待推送任务：' . date('Y-m-d H:i:s') . "\n";
        }
        
        addlog('TaskPushTorrentProcess', "pushReleaseTorrent任务ID：{$item->id}，站点ID：{$item->site_id}，下载器ID：{$item->downloader_id}-开始");
        
        try {
            $result = DownloaderWorkService::pushReleaseTorrent($item);
            
            if ($result) {
                addlog('TaskPushTorrentProcess', "pushReleaseTorrent任务ID：{$item->id}-成功");
            } else {
                addlog('TaskPushTorrentProcess', "pushReleaseTorrent任务ID：{$item->id}-失败");
            }
        } catch (\Throwable $e) {
            addlog('TaskPushTorrentProcess', "pushReleaseTorrent任务ID：{$item->id}-异常：{$e->getMessage()}");
            
            // 更新时间戳，避免重复处理
            $item->updated_at = date('Y-m-d H:i:s');
            $item->save();
        }
        
        return '任务调用：' . date('Y-m-d H:i:s') . "\n";
    }

    /**
     * 停止/删除定时器
     *
     * @return bool
     */
    public function stop()
    {
        return Timer::del($this->timer);
    }
}
